import java.util.HashMap;
import java.util.Map;

public class LRUCache {
    class DLinkedNode {
        int key;
        int val;
        DLinkedNode prev;
        DLinkedNode next;
        public DLinkedNode(){}

        public DLinkedNode(int key, int val){
            this.key = key;
            this.val = val;
        }
    }
    Map<Integer, DLinkedNode> map = new HashMap<>();
    int size;
    int capacity;
    private DLinkedNode head, tail;

    public LRUCache(int capacity) {
        this.size = 0;
        this.capacity = capacity;
        head = new DLinkedNode();
        tail = new DLinkedNode();
        head.next = tail;
        tail.prev = head;
    }

    public int get(int key) {
        DLinkedNode node = map.get(key);
        if(node == null){
            return -1;
        }
        remove(node);
        addToHead(node);
        return node.val;
    }

    public void put(int key, int value) {
        DLinkedNode node = map.get(key);
        if(node == null){
            node = new DLinkedNode(key, value);
            addToHead(node);
            map.put(key, node);
            size++;
            if(size > capacity){
                map.remove(tail.prev.key);
                remove(tail.prev);
                size--;
            }

        } else {
            remove(node);
            node.val = value;
            addToHead(node);
        }

    }

    private void addToHead(DLinkedNode node) {
        node.prev = head;
        node.next = head.next;
        head.next.prev = node;
        head.next = node;
    }

    private void remove(DLinkedNode node) {
        node.prev.next = node.next;
        node.next.prev = node.prev;
    }
}

